package com.Aspect;

import com.controller.User;
import com.dao.UserMapper;
import com.service.UserService;
import com.service.UserServiceImpl;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


//切面类
@Component
@Aspect
public class LogAspect {

    private SqlSession sqlSession;

    //获取userMapper
    public UserMapper getUserMapper(){
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        final SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = build.openSession();
        final UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        return userMapper;
    }

    //给登录功能添加后置通知
    @AfterReturning("execution(* com.service.UserServiceImpl." +
            "selectUserByUsernameAndPassword(..)) && args(username,password)")
    public void loginUserLog(String username, String password){
        //获取userMapper
        final UserMapper userMapper = this.getUserMapper();
        //获取当前日期
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //执行被增强的方法
        userMapper.loginUserLog(username,"登录",dateFormat.format(date));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    //给注册功能添加后置通知
    @AfterReturning("execution(* com.service.UserServiceImpl." +
            "addUser(..)) && args(user))")
    public void registerLog(User user){
        //获取userMapper
        final UserMapper userMapper = this.getUserMapper();
        //获取当前日期
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //执行被增强的方法
        userMapper.registerLog(user,"注册",dateFormat.format(date));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}
